//
//  PullToRefreshDemo.swift
//  Swift-30-demo
//
//  Created by apple on 2021/11/29.
//

import UIKit
import PullToRefreshKit

class PullToRefreshDemo: UIViewController, UITableViewDelegate, UITableViewDataSource {
    var dataSource = Array<Date>()
    var dataTable : UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.navigationItem.title = "PullToRefreshDemo"
        self.view.backgroundColor = UIColor.white
        // Do any additional setup after loading the view.
        createMainView()
    }
    
    func createMainView() {
        dataTable = UITableView()
        dataTable.delegate = self
        dataTable.dataSource = self
        self.view.addSubview(dataTable)
        dataTable.snp.makeConstraints { make in
            make.top.equalTo(navgationHeight)
            make.leading.trailing.equalTo(self.view)
            make.bottom.equalTo(self.view)
        }
        
        addNewElementToArray()
        
        dataTable.configRefreshHeader(container: self, action: { [weak self] in
            print("excute refreshBlock")
            self?.refresh()
        })
        
        dataTable.configRefreshFooter(container: self, action: { [weak self] in
            print("excute loadMoreBlock")
            self?.footerRefresh()
        })
    }
    
    func refresh() {
        dataSource.removeAll()
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) { [self] in
            dataTable.switchRefreshHeader(to: .normal(.success, 0.5))
            // dataTable.switchRefreshHeader(to: .normal(.none, 0))
            addNewElementToArray()
        }
    }
    
    func footerRefresh() {
        DispatchQueue.main.asyncAfter(deadline: .now() + 1) { [self] in
            dataTable.switchRefreshFooter(to: .normal)
            // dataTable.switchRefreshFooter(to: .removed)
            // dataTable.switchRefreshFooter(to: .noMoreData)
            addNewElementToArray()
            print(dataSource)
        }
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSource.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: "reuseCellForPullToRefresh")
        
        let dateFormatter = DateFormatter()
        dateFormatter.dateFormat = "yyyy年MM月dd日/HH时mm分ss秒"
        let dateStr = dateFormatter.string(from: dataSource[indexPath.row])
        cell.textLabel?.text = dateStr
        return cell
    }
    
    func addNewElementToArray() {
        dataSource.insert(NSDate() as Date, at: 0)
        dataTable.reloadData()
    }
}
